package com.zprmb.udzt.util;

//import java.math.BigDecimal;
//import java.math.MathContext;
//import java.util.ArrayList;
//import java.util.Calendar;
//import java.util.Date;
//import java.util.List;
//
//
//
///**
// * Created by lxl on 15/7/1.
// */
//public class LoanCalculator {
//
//    private static final BigDecimal ZERO = new BigDecimal(0).setScale(2);
//
//    private static final BigDecimal ONE = new BigDecimal(1).setScale(2);
//
//    private static final BigDecimal monthsPerYear = new BigDecimal(TimeConstant.MONTHS_PER_YEAR);
//
//    private static final BigDecimal daysPerYear = new BigDecimal(TimeConstant.DAYS_PER_YEAR);
//
//    /**
//     * rate is in format like 2400 which is actually 24.00%
//     */
//    private static final BigDecimal rateScale = new BigDecimal(10000);
//
//    private static final MathContext mc = new MathContext(16, NumberConstant.ROUNDING_MODE);
//
//    /**
//     * @param amount
//     * @param duration
//     * @param rate     2400 means 24.00%
//     * @param method
//     * @param asOfDate
//     * @return
//     */
////    public static RmbLoanDetail analyze(final int amount,
////                                        final Duration duration,
////                                        final int rate,
////                                        final RmbRepayMethod method,
////                                        final LocalDate asOfDate) {
////        return analyze(BigDecimal.valueOf(amount), duration, rate, method, asOfDate);
////    }
//
//    /**
//     * @param amount
//     * @param duration
//     * @param rate     2400 means 24.00%
//     * @param method
//     * @param asOfDate
//     * @return
//     */
////    public static RmbLoanDetail analyze(final BigDecimal amount,
////                                        final Duration duration,
////                                        final int rate,
////                                        final RmbRepayMethod method,
////                                        final LocalDate asOfDate) {
////        RmbLoanDetail result = null;
////        //principal
////        BigDecimal principal = amount;
////        //now get rates
////        BigDecimal rateYear = new BigDecimal(rate).divide(rateScale, mc);
////        BigDecimal rateMonth = rateYear.divide(monthsPerYear, mc);
////        BigDecimal rateDay = rateYear.divide(daysPerYear, mc);
////        //dealing with different methods 
////        BigDecimal interest, amortizedInterest, amortizedPrincipal, outstandingPrincipal;
////        LocalDate dueDate = asOfDate;
////        int tenure;
////        switch (method) {
////            case BulletRepayment:
////                //add yearly interest
////                interest = principal.multiply(rateYear).multiply(new BigDecimal(duration.getYears()));
////                //add monthly interest
////                interest = interest.add(principal.multiply(rateMonth).multiply(new BigDecimal(duration.getMonths())));
////                //add daily interest
////                interest = interest.add(principal.multiply(rateDay).multiply(new BigDecimal(duration.getDays())));
////                //ceilling the interest
////                interest = interest.setScale(2, NumberConstant.ROUNDING_MODE);
////                //create result
////                result = new RmbLoanDetail(principal, interest, duration, RmbRepayMethod.BulletRepayment);
////                //add single amortize item
////                result.getRepayments().add(new Repayment(principal, interest, ZERO, DateUtils.offset(asOfDate, duration)));
////                break;
////            case MonthlyInterest:   //in this case we don't need to worry about duration.days since that must be 0
////                amortizedInterest = principal.multiply(rateMonth).setScale(2, NumberConstant.ROUNDING_MODE);
////                interest = amortizedInterest.multiply(new BigDecimal(duration.getTotalMonths()));
////                //create result
////                result = new RmbLoanDetail(principal, interest, duration, RmbRepayMethod.MonthlyInterest);
////                //add amortized items
////                for (int i = 0; i < duration.getTotalMonths(); i++) {
////                    dueDate = DateUtils.offset(dueDate, new Duration(0, 1, 0));
////                    if (i < duration.getTotalMonths() - 1) {    //only interest, no principal
////                        result.getRepayments().add(new Repayment(ZERO, amortizedInterest, principal, dueDate));
////                    } else {    //last ONE we pay off the principal as well as interest
////                        result.getRepayments().add(new Repayment(principal, amortizedInterest, ZERO, dueDate));
////                    }
////                }
////                break;
////            case EqualInstallment:
////                //times of repayments in months
////                tenure = duration.getYears() * 12 + duration.getMonths();
////                //pre-calc
////                BigDecimal[] is = new BigDecimal[tenure + 1];
////                for (int i = 0; i <= tenure; i++) {
////                    is[i] = rateMonth.add(ONE).pow(i);
////                }
////                BigDecimal baseInterest = principal.multiply(rateMonth);
////                //calc installment
////                BigDecimal installment = baseInterest.multiply(is[tenure]).divide(is[tenure].subtract(ONE), mc);
////                installment = installment.setScale(2, NumberConstant.ROUNDING_MODE);
////                //reset total interest
////                interest = ZERO;
////                //create loanDetail
////                result = new RmbLoanDetail(principal, interest, duration, RmbRepayMethod.EqualInstallment);
////                //deal with amortized items
////                outstandingPrincipal = principal;
////                for (int i = 0; i < tenure; i++) {
////                    dueDate = DateUtils.offset(dueDate, new Duration(0, 1, 0));
////                    amortizedInterest = baseInterest.subtract(installment, mc).multiply(is[i]).add(installment, mc).setScale(2, NumberConstant.ROUNDING_MODE);
////                    amortizedPrincipal = installment.subtract(amortizedInterest);
////                    outstandingPrincipal = outstandingPrincipal.subtract(amortizedPrincipal);
////                    if (i == tenure - 1) {  //last ONE we need to fix the rounding error and let the oustanding principal be ZERO
////                        result.getRepayments().add(new Repayment(amortizedPrincipal.add(outstandingPrincipal),
////                                amortizedInterest,
////                                ZERO,
////                                dueDate));
////                    } else {
////                        result.getRepayments().add(new Repayment(amortizedPrincipal,
////                                amortizedInterest,
////                                outstandingPrincipal,
////                                dueDate));
////                    }
////                    interest = interest.add(amortizedInterest);
////                }
////                //fix interest
////                result.setInterest(interest);
////                break;
////            case EqualPrincipal:
////                //times of repayments in months
////                tenure = duration.getYears() * 12 + duration.getMonths();
////                //calc amortized principal first
////                amortizedPrincipal = principal.divide(new BigDecimal(tenure == 0 ? 1 : tenure), mc).setScale(2, NumberConstant.ROUNDING_MODE);
////                //calc by each month
////                BigDecimal[] interests = new BigDecimal[tenure];
////                BigDecimal[] outstandingPrincipals = new BigDecimal[tenure];
////                outstandingPrincipal = principal;
////                interest = ZERO;
////                for (int i = 0; i < tenure; i++) {
////                    interests[i] = outstandingPrincipal.multiply(rateMonth, mc).setScale(2, NumberConstant.ROUNDING_MODE);
////                    interest = interest.add(interests[i]);
////                    outstandingPrincipal = outstandingPrincipal.subtract(amortizedPrincipal);
////                    outstandingPrincipals[i] = outstandingPrincipal;
////                }
////                //create LoanDetail
////                result = new RmbLoanDetail(principal, interest, duration, RmbRepayMethod.EqualPrincipal);
////                //deal with amortized items
////                for (int i = 0; i < tenure; i++) {
////                    dueDate = DateUtils.offset(dueDate, new Duration(0, 1, 0));
////                    if (i == tenure - 1) {
////                        result.getRepayments().add(new Repayment(amortizedPrincipal.add(outstandingPrincipals[i]),
////                                interests[i],
////                                ZERO,
////                                dueDate));
////                    } else {
////                        result.getRepayments().add(new Repayment(amortizedPrincipal,
////                                interests[i],
////                                outstandingPrincipals[i],
////                                dueDate));
////                    }
////                }
////                break;
////            case EqualInterest:
////                //times of repayments in months
////                tenure = duration.getYears() * 12 + duration.getMonths();
////                //calc amortized principal and interest
////                amortizedPrincipal = principal.divide(new BigDecimal(tenure), mc).setScale(2, NumberConstant.ROUNDING_MODE);
////                amortizedInterest = principal.multiply(rateMonth).setScale(2, NumberConstant.ROUNDING_MODE);
////                interest = amortizedInterest.multiply(new BigDecimal(tenure), mc).setScale(2, NumberConstant.ROUNDING_MODE);
////                //create LoanDetail
////                result = new RmbLoanDetail(principal, interest, duration, RmbRepayMethod.EqualInterest);
////                //deal with amortized items
////                outstandingPrincipal = principal;
////                for (int i = 0; i < tenure; i++) {
////                    outstandingPrincipal = outstandingPrincipal.subtract(amortizedPrincipal);
////                    dueDate = DateUtils.offset(dueDate, new Duration(0, 1, 0));
////                    if (i == tenure - 1) {
////                        result.getRepayments().add(new Repayment(amortizedPrincipal.add(outstandingPrincipal),
////                                amortizedInterest,
////                                ZERO,
////                                dueDate));
////                    } else {
////                        result.getRepayments().add(new Repayment(amortizedPrincipal,
////                                amortizedInterest,
////                                outstandingPrincipal,
////                                dueDate));
////                    }
////                }
////                break;
////        }
////        return result;
////    }
//
//    /**
//     * V3.0
//     *
//     * */
//    public static RmbLoanDetail analyze(final BigDecimal amount,
//                                        final Duration duration,
//                                        final BigDecimal rate,
//                                        final RmbRepayMethod method,
//                                        final String date) {
//        RmbLoanDetail result = null;
//        // 第1步：从今天开始，计算一共投资的天数
//        String[] dateStrArr = date.split("-");
//        if (dateStrArr.length == 0) {
//            dateStrArr = date.split("/");
//        }
//        Calendar dt1 = Calendar.getInstance();
//        Calendar dt2 = Calendar.getInstance();
//        if (dateStrArr.length == 0) {
//            dt1.set(dt1.get(Calendar.YEAR), dt1.get(Calendar.MONTH),
//                    dt1.get(Calendar.DATE));
//            dt2.set(dt2.get(Calendar.YEAR), dt2.get(Calendar.MONTH),
//                    dt2.get(Calendar.DATE));
//        } else {
//            dt1.set(Integer.parseInt(dateStrArr[0]),
//                    Integer.parseInt(dateStrArr[1]) - 1,
//                    Integer.parseInt(dateStrArr[2]));
//            dt2.set(Integer.parseInt(dateStrArr[0]),
//                    Integer.parseInt(dateStrArr[1]) - 1,
//                    Integer.parseInt(dateStrArr[2]));
//        }
//        dt2.add(Calendar.YEAR, duration.getYears());
//        dt2.add(Calendar.MONTH, duration.getMonths());
//        dt2.add(Calendar.DAY_OF_YEAR, duration.getDays());
//
//        long daterange = dt2.getTimeInMillis() - dt1.getTimeInMillis();
//        Double oneday = Double.parseDouble(String.valueOf(1000 * 3600 * 24)); // A
//        // day
//        // in
//        // milliseconds
//
//        int totalDays = (int) Math.round(Double.parseDouble(String
//                .valueOf(daterange)) / oneday);
//        int totalMonths = duration.getYears() * 12 + duration.getMonths();
//        int leftDays = duration.getDays(); // 这里按月付息/等额本金/等额本息 需要使用计算剩余的
//        BigDecimal interest = new BigDecimal("0");
//
//        // return format <timeSpan, amount, principal, interest, leftPrincipal,
//        // this duration days>
//        List<List<Object>> list = new ArrayList<>();
//        result = new RmbLoanDetail(amount, BigDecimal.ZERO, duration, method);
//        switch (method) {
//            case MonthlyInterest:// 按月付息，到期还本
//            	Calendar repayCalendar = null;
//                for (int i = 1; i <= totalMonths; i++) {
//                	repayCalendar = Calendar.getInstance();
//                	repayCalendar.set(Integer.parseInt(dateStrArr[0]),
//                            Integer.parseInt(dateStrArr[1]) - 1,
//                            Integer.parseInt(dateStrArr[2]));
//                    Calendar tempCalendar = Calendar.getInstance();
//                    if (dateStrArr.length == 0) {
//                        tempCalendar.set(tempCalendar.get(Calendar.YEAR),
//                                tempCalendar.get(Calendar.MONTH),
//                                tempCalendar.get(Calendar.DATE));
//                    } else {
//                        tempCalendar.set(Integer.parseInt(dateStrArr[0]),
//                                Integer.parseInt(dateStrArr[1]) - 1,
//                                Integer.parseInt(dateStrArr[2]));
//                    }
//                    tempCalendar.add(Calendar.MONTH, i - 1);
//                    repayCalendar.add(Calendar.MONTH, i);//根据结算日期计算还款日期
//                    // 计算当月投资范围的天数
//                    int tempDays = (int) Math.round(Double.parseDouble(String
//                            .valueOf(repayCalendar.getTimeInMillis()
//                                    - tempCalendar.getTimeInMillis()))
//                            / oneday);
//                    interest = amount
//                            .multiply(rate)
//                            .divide(new BigDecimal("10000"), MathContext.DECIMAL128)
//                            .divide(new BigDecimal("365"), MathContext.DECIMAL128)
//                            .multiply(new BigDecimal(Integer.toString(tempDays))); // 金额*利率/365*天数
//                    List<Object> item = new ArrayList<>();
//                    item.add(repayCalendar.getTimeInMillis());
//                    if (i == totalMonths && leftDays == 0) {
//                        item.add(amount.add(interest));
//                        item.add(amount);
//                    } else {
//                        item.add(interest);
//                        item.add(0);
//                    }
//                    item.add(interest);
//                    if (i == totalMonths && leftDays == 0) {
//                        item.add(0);
//                    } else {
//                        item.add(amount);
//                    }
//                    item.add(tempDays);
//                    result.getRepayments().add(convertToRepayment(item));
//                }
//                // 如果有剩余天数，剩余的利息按天计
//                if (leftDays > 0) {
//                	repayCalendar.add(Calendar.DAY_OF_YEAR, leftDays); // 加剩余的天数
//                    interest = amount
//                            .multiply(rate)
//                            .divide(new BigDecimal("10000"), MathContext.DECIMAL128)
//                            .divide(new BigDecimal("365"), MathContext.DECIMAL128)
//                            .multiply(new BigDecimal(Integer.toString(leftDays))); // 金额*利率/365*天数
//                    List<Object> item = new ArrayList<>();
//                    item.add(repayCalendar.getTimeInMillis());
//                    item.add(amount.add(interest));
//                    item.add(amount);
//                    item.add(interest);
//                    item.add(0);
//                    item.add(leftDays);
//
//                    result.getRepayments().add(convertToRepayment(item));
//                }
//                break;
//            case EqualInstallment:// 按月等额本息，只考虑totalMonths?
//                BigDecimal monthRate = rate.divide(new BigDecimal("10000"),
//                        MathContext.DECIMAL128).divide(new BigDecimal("12"),
//                        MathContext.DECIMAL128);
//                BigDecimal monthReturn = amount
//                        .multiply(monthRate)
//                        .multiply(
//                                monthRate.add(new BigDecimal("1")).pow(totalMonths))
//                        .divide(monthRate.add(new BigDecimal("1")).pow(totalMonths)
//                                        .subtract(new BigDecimal("1")),
//                                MathContext.DECIMAL128);
//                BigDecimal tempAmount = amount;
//                for (int i = 1; i <= totalMonths; i++) {
//                	repayCalendar = Calendar.getInstance();
//                	repayCalendar.set(Integer.parseInt(dateStrArr[0]),
//                			Integer.parseInt(dateStrArr[1]) - 1,
//                			Integer.parseInt(dateStrArr[2]));
//                    Calendar tempCalendar = Calendar.getInstance();
//                    tempCalendar.set(tempCalendar.get(Calendar.YEAR),
//                            tempCalendar.get(Calendar.MONTH),
//                            tempCalendar.get(Calendar.DATE));
//                    tempCalendar.add(Calendar.MONTH, i - 1);
//                    repayCalendar.add(Calendar.MONTH, i); // 每次都加1个月
//                    // 计算当月投资范围的天数
//                    int tempDays = (int) Math.round(Double.parseDouble(String
//                            .valueOf(repayCalendar.getTimeInMillis()
//                                    - tempCalendar.getTimeInMillis()))
//                            / oneday);
//                    interest = amount
//                            .multiply(monthRate)
//                            .multiply(
//                                    monthRate
//                                            .add(new BigDecimal("1"))
//                                            .pow(totalMonths)
//                                            .subtract(
//                                                    monthRate.add(
//                                                            new BigDecimal("1"))
//                                                            .pow(i - 1)))
//                            .divide(monthRate.add(new BigDecimal("1"))
//                                            .pow(totalMonths).subtract(new BigDecimal("1")),
//                                    MathContext.DECIMAL128);// amount*monthRate*(Math.pow(1+monthRate,
//                    // totalMonths)-Math.pow(1+monthRate,i-1))/(Math.pow(1+monthRate,totalMonths)-1);
//                    tempAmount = tempAmount.subtract(monthReturn).add(interest);
//                    List<Object> item = new ArrayList<>();
//                    item.add(repayCalendar.getTimeInMillis());
//                    item.add(monthReturn);
//                    item.add(monthReturn.subtract(interest));
//                    item.add(interest);
//                    item.add(tempAmount);
//                    item.add(tempDays);
//
//                    result.getRepayments().add(convertToRepayment(item));
//                }
//                break;
//            case EqualPrincipal:// 按月等额本金
//                monthRate = rate.divide(new BigDecimal("10000"),
//                        MathContext.DECIMAL128).divide(new BigDecimal("12"),
//                        MathContext.DECIMAL128);
//                BigDecimal monthPrincipal = amount.divide(
//                        new BigDecimal(Integer.toString(totalMonths)),
//                        MathContext.DECIMAL128); // 每月应还本金=贷款本金÷还款月数
//                tempAmount = amount;
//                for (int i = 1; i <= totalMonths; i++) {
//                	repayCalendar = Calendar.getInstance();
//                	repayCalendar.set(Integer.parseInt(dateStrArr[0]),
//                			Integer.parseInt(dateStrArr[1]) - 1,
//                			Integer.parseInt(dateStrArr[2]));
//                    Calendar tempCalendar = Calendar.getInstance();
//                    tempCalendar.set(tempCalendar.get(Calendar.YEAR),
//                            tempCalendar.get(Calendar.MONTH),
//                            tempCalendar.get(Calendar.DATE));
//                    tempCalendar.add(Calendar.MONTH, i - 1);
//                    repayCalendar.add(Calendar.MONTH, i); // 每次都加1个月
//                    // 计算当月投资范围的天数
//                    int tempDays = (int) Math.round(Double.parseDouble(String
//                            .valueOf(repayCalendar.getTimeInMillis()
//                                    - tempCalendar.getTimeInMillis()))
//                            / oneday);
//                    interest = tempAmount.multiply(monthRate); // 每月应还利息=剩余本金×月利率
//                    tempAmount = tempAmount.subtract(monthPrincipal);
//                    List<Object> item = new ArrayList<>();
//                    item.add(repayCalendar.getTimeInMillis());
//                    item.add(monthPrincipal.add(interest));
//                    item.add(monthPrincipal);
//                    item.add(interest);
//                    item.add(tempAmount);
//                    item.add(tempDays);
//
//                    result.getRepayments().add(convertToRepayment(item));
//                }
//                break;
//            case EqualInterest: // 月平息
//            case BulletRepayment: // 一次性还本付息
//            default: // 月平息暂时不用，所以按默认的来了
//                interest = amount.multiply(rate)
//                        .divide(new BigDecimal("10000"), MathContext.DECIMAL128)
//                        .divide(new BigDecimal("365"), MathContext.DECIMAL128)
//                        .multiply(new BigDecimal(Integer.toString(totalDays))); // 金额*利率/365*天数
//                List<Object> item = new ArrayList<>();
//                item.add(dt2.getTimeInMillis());
//                item.add(amount.add(interest));
//                item.add(amount);
//                item.add(interest);
//                item.add(0);
//                item.add(totalDays);
//                result.getRepayments().add(convertToRepayment(item));
//                break;
//        }
//
//
//        return result;
//    }
//
//    private static Repayment convertToRepayment(List<Object> list){
//        BigDecimal amountPrincipal = new BigDecimal(list.get(2).toString()).setScale(2,BigDecimal.ROUND_HALF_UP);
//        BigDecimal amountInterest = new BigDecimal(list.get(3).toString()).setScale(2,BigDecimal.ROUND_HALF_UP);
//        BigDecimal amountOutstanding =new BigDecimal(list.get(4).toString()).setScale(2,BigDecimal.ROUND_HALF_UP);
//        Date dueDate = new Date(Long.parseLong(list.get(0).toString()));
//        return  new Repayment(amountPrincipal,amountInterest,amountOutstanding,dueDate);
//    }
//}
